package com.tcfvic.client.panels.widgets.widgetcontents;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.tcfvic.client.PersonService;
import com.tcfvic.client.PersonServiceAsync;
import com.tcfvic.client.panels.widgets.SimpleMessagePopup;
import com.tcfvic.client.panels.widgets.TCFWidgetContent;
import com.tcfvic.client.pojos.Employmentstatus;
import com.tcfvic.client.pojos.EmploymentstatusId;
import com.tcfvic.client.pojos.Industry;
import com.tcfvic.client.pojos.Person;
import com.tcfvic.client.tools.Month;
import com.tcfvic.client.tools.Tools;

public class EmployStatusTab extends AbstractDataEntryWidgets implements
		TCFWidgetContent {

	/**
	 * Create a remote service proxy to talk to the server-side PersonDetails
	 * service.
	 */
	private final PersonServiceAsync personService = GWT
			.create(PersonService.class);
	private FlexTable empStatusTable = null;
	private FlexTable tabContentFlexTable = null;
	// private Map<Integer, List<Personcourse>> personCoursesByFundingID = new
	// HashMap<Integer, List<Personcourse>>();
	private String currentPersonRowId = "";

	public EmployStatusTab() {
		// initialise();
	}

	public String getName() {
		return "Emp. Status";
	}

	@Override
	public Widget getContent() {
		final Button moveToRight = new Button("Add status");

		// Create a table to layout the form options
		tabContentFlexTable = new FlexTable();
		tabContentFlexTable.setCellSpacing(3);
		tabContentFlexTable.setWidth("100%");

		moveToRight.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				addEmpStatus("", "", "", "", "", "", "", "", "", null, null,
						"", "", "", "", "", "", "");
			}
		});
		moveToRight.ensureDebugId("cwBasicButton-normal");

		// add buttons panel to flex table
		tabContentFlexTable.setWidget(0, 0, moveToRight);

		setupStatusList();

		// SAVE button
		saveButton.getElement().setId("saveButton");
		tabContentFlexTable.setWidget(3, 0, saveButton);

		return tabContentFlexTable;
	}

	public void setupStatusList() {
		// Create a Flex Table
		int col = 0;
		FlexTable flexTable = new FlexTable();
		flexTable.addStyleName("cw-FlexTable");
		flexTable.setWidth("32em");
		flexTable.setCellSpacing(1);
		flexTable.setCellPadding(1);
		// flexTable.setHTML(0, col++, "ID");
		// col++; // increasing col number because I have commented out the
		// above
		// line
		flexTable.setHTML(0, col++, "ID");
		flexTable.setHTML(0, col++, "Employment status");
		flexTable.setHTML(0, col++, "Reason for unemployment");
		flexTable.setHTML(0, col++, "Type of work");
		flexTable.setHTML(0, col++, "Hours of work");
		flexTable.setHTML(0, col++, "Role / Position");
		flexTable.setHTML(0, col++, "Company");
		flexTable.setHTML(0, col++, "Industry");
		flexTable.setHTML(0, col++, "Size of company");
		flexTable.setHTML(0, col++, "Suburb");
		flexTable.setHTML(0, col++, "State");
		// flexTable.setHTML(0, col++, "No hrs employed weekly");
		// flexTable.setHTML(0, col++, "Need/want more hours");
		flexTable.setHTML(0, col++, "Start date");
		flexTable.setHTML(0, col++, "End date");
		flexTable.setHTML(0, col++, "Work conditions");
		flexTable.setHTML(0, col++, "Joined a union?");
		flexTable.setHTML(0, col++, "Reason for leaving");
		flexTable.setHTML(0, col++, "Notes (ES)");

		flexTable.setBorderWidth(1);
		empStatusTable = flexTable;

		tabContentFlexTable.setWidget(1, 0, empStatusTable);
		tabContentFlexTable.getFlexCellFormatter().setColSpan(1, 0, 4);
	}

	public void addEmpStatus(String employmentStatus, String reasonForUnempl,
			String notes, String jobRole, String nameOfEmployer, String suburb,
			String state, String sizeOfCompany, String industry,
			Date startDate, Date endDate, String typeOfWork,
			String hoursOfWork, String noOfHrsEmployedWeekly,
			String needWantMoreHours, String workingConditions,
			String unionMember, String reasonForLeaving) {

		final int numRows = empStatusTable.getRowCount();
		int col = 0;
		empStatusTable.setWidget(numRows, col++, new HTML(String
				.valueOf(numRows)));

		ListBox lb = getEmploymentStatus(employmentStatus);
		empStatusTable.setWidget(numRows, col++, lb);

		lb = getReasonForUnempl(reasonForUnempl);
		empStatusTable.setWidget(numRows, col++, lb);

		lb = getTypeWorkList(typeOfWork);
		empStatusTable.setWidget(numRows, col++, lb);

		lb = getHoursOfWorkList(hoursOfWork);
		empStatusTable.setWidget(numRows, col++, lb);

		TextBox jobRoleTB = new TextBox();
		jobRoleTB.setText(jobRole);
		empStatusTable.setWidget(numRows, col++, jobRoleTB);

		TextBox nameTB = new TextBox();
		nameTB.setText(nameOfEmployer);
		empStatusTable.setWidget(numRows, col++, nameTB);

		lb = getIndustryList(industry);
		empStatusTable.setWidget(numRows, col++, lb);

		lb = getSizeCompList(sizeOfCompany);
		empStatusTable.setWidget(numRows, col++, lb);

		TextBox suburgTB = new TextBox();
		suburgTB.setText(suburb);
		empStatusTable.setWidget(numRows, col++, suburgTB);

		lb = Tools.getStatesListBox();
		lb.setSelectedIndex(Tools.getSelectedIndex(lb, state));
		empStatusTable.setWidget(numRows, col++, lb);

		// start date
		HorizontalPanel hp = new HorizontalPanel();
		ListBox dayStart = Tools.getDayListBox();
		ListBox monthStart = Tools.getMonthListBox();
		ListBox yearStart = Tools.getYearListBox(2000);
		hp.add(dayStart);
		hp.add(monthStart);
		hp.add(yearStart);
		try {
			dayStart.setSelectedIndex(Tools.getSelectedIndexBasedOnItem(
					dayStart, Tools.getDay(startDate)));
			monthStart.setSelectedIndex(Month.valueOf(
					Tools.getMonth(startDate).toUpperCase()).getId());
			yearStart.setSelectedIndex(Tools.getSelectedIndex(yearStart, Tools
					.getYear(startDate)));
		} catch (Exception e) {
		}
		empStatusTable.setWidget(numRows, col++, hp);

		// finish date
		hp = new HorizontalPanel();
		dayStart = Tools.getDayListBox();
		monthStart = Tools.getMonthListBox();
		yearStart = Tools.getYearListBox(2000);
		hp.add(dayStart);
		hp.add(monthStart);
		hp.add(yearStart);
		try {
			dayStart.setSelectedIndex(Tools.getSelectedIndexBasedOnItem(
					dayStart, Tools.getDay(endDate)));
			monthStart.setSelectedIndex(Month.valueOf(
					Tools.getMonth(endDate).toUpperCase()).getId());
			yearStart.setSelectedIndex(Tools.getSelectedIndex(yearStart, Tools
					.getYear(endDate)));
		} catch (Exception e) {
		}
		empStatusTable.setWidget(numRows, col++, hp);

		lb = getWorkingConditionsList(workingConditions);
		empStatusTable.setWidget(numRows, col++, lb);

		lb = Tools.getYesNoList();
		lb.setSelectedIndex(Tools.getSelectedIndex(lb, unionMember));
		empStatusTable.setWidget(numRows, col++, lb);

		lb = getReasonForLeaving(reasonForLeaving);
		empStatusTable.setWidget(numRows, col++, lb);

		TextBox notesTB = new TextBox();
		notesTB.setText(notes);
		empStatusTable.setWidget(numRows, col++, notesTB);

		// TextBox noHourTB = new TextBox();
		// noHourTB.setText(noOfHrsEmployedWeekly);
		// empStatusTable.setWidget(numRows, col++, noHourTB);
		//
		// lb = Tools.getYesNoList();
		// lb.setSelectedIndex(Tools.getSelectedIndex(lb, needWantMoreHours));
		// empStatusTable.setWidget(numRows, col++, lb);

		Hyperlink link = new Hyperlink("Remove", String.valueOf(numRows));
		link.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Hyperlink link = (Hyperlink) event.getSource();
				removeRow(link.getTargetHistoryToken());
			}
		});
		empStatusTable.setWidget(numRows, col++, link);
	}

	private ListBox getIndustryList(final String industrySelected) {
		final ListBox lb = new ListBox();
		personService.getAllIndustries(new AsyncCallback<List<Industry>>() {
			@Override
			public void onSuccess(List<Industry> result) {
				lb.addItem("", "");
				for (Industry industry : result) {
					lb.addItem(industry.getName(), String.valueOf(industry
							.getId()));
				}
				if (industrySelected != null) {
					lb.setSelectedIndex(Tools.getSelectedIndexBasedOnItem(lb,
							industrySelected));
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		});
		return lb;
	}

	private ListBox getReasonForUnempl(String empStatus) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Forced to retire", "Forced to retire");
		lb.addItem("Chose to retire", "Chose to retire");
		lb.addItem("Workcover", "Workcover");
		lb.addItem("Other health issue", "Other health issue");
		lb.addItem("Caring responsibilities", "Caring responsibilities");
		lb.addItem("Taking a break", "Taking a break");
		lb.addItem("Volunteering", "Volunteering");
		lb.addItem("Training", "Training");
		lb.addItem("Looking for work", "Looking for work");
		lb.addItem("Work experience", "Work experience");
		if (empStatus != null && !empStatus.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, empStatus));
		}
		return lb;
	}

	private ListBox getReasonForLeaving(String empStatus) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Terminated", "Terminated");
		lb.addItem("Left the job", "Left the job");
		lb.addItem("Job finished", "Job finished");
		if (empStatus != null && !empStatus.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, empStatus));
		}
		return lb;
	}

	private ListBox getEmploymentStatus(String empStatus) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Employed", "Employed");
		lb.addItem("Unemployed", "Unemployed");
		if (empStatus != null && !empStatus.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, empStatus));
		}
		return lb;
	}
	
	private ListBox getSizeCompList(String size) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("1-10", "1-10");
		lb.addItem("11-20", "11-20");
		lb.addItem("21-50", "21-50");
		lb.addItem("51-100", "51-100");
		lb.addItem("100+", "100+");
		if (size != null && !size.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, size));
		}
		return lb;
	}

	private ListBox getTypeWorkList(String typeOfWork) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Permanent", "Permanent");
		lb.addItem("Casual", "Casual");
		lb.addItem("Contract", "Contract");
		lb.addItem("Homework", "Homework");
		lb.addItem("Volunteer", "Volunteer");
		if (typeOfWork != null && !typeOfWork.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, typeOfWork));
		}
		return lb;
	}

	private ListBox getHoursOfWorkList(String hoursOfWork) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Full Time", "Full Time");
		lb.addItem("Part Time", "Part Time");
		if (hoursOfWork != null && !hoursOfWork.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, hoursOfWork));
		}
		return lb;
	}

	private ListBox getWorkingConditionsList(String workingConditions) {
		ListBox lb = new ListBox();
		lb.addItem("", "");
		lb.addItem("Enterprise Agreement", "Enterprise Agreement");
		lb.addItem("Award", "Award");
		lb.addItem("Common Law Contract", "Common Law Contract");
		lb.addItem("Do not know", "Do not know");
		if (workingConditions != null && !workingConditions.isEmpty()) {
			lb.setSelectedIndex(Tools.getSelectedIndex(lb, workingConditions));
		}
		return lb;
	}

	private void removeRow(String id) {
		for (int i = 1; i < empStatusTable.getRowCount(); i++) {
			HTML rowID = (HTML) empStatusTable.getWidget(i, 0);
			if (rowID.getText().equals(id)) {
				empStatusTable.removeRow(i);
				break;
			}
		}
	}

	public void clear() {
		while (empStatusTable.getRowCount() > 1) {
			empStatusTable.removeRow(1);
		}
	}

	public void updateContent(Object o) {
		if (o != null) {
			Person p = (Person) o;
			currentPersonRowId = String.valueOf(p.getId());
			initialise();
		}
	}

	@Override
	public void initialise() {
		if (currentPersonRowId.length() > 0) {
			personService.getEmploymentStatus(Integer
					.valueOf(currentPersonRowId),
					new AsyncCallback<List<Employmentstatus>>() {
						@Override
						public void onSuccess(List<Employmentstatus> result) {
							populateEmploymentStatus(result);
						}

						@Override
						public void onFailure(Throwable caught) {
							new SimpleMessagePopup(
									"Error occured getting the person-course data",
									null).showPopup();
						}
					});
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T saveContent(T t) throws NumberFormatException, Exception {
		Person person = (Person) t;
		List<Employmentstatus> statusList = null;
		if (empStatusTable.getRowCount() > 1) {
			statusList = new ArrayList<Employmentstatus>();
			for (int i = 1; i < empStatusTable.getRowCount(); i++) {
				int colId = 0;
				Employmentstatus status = new Employmentstatus();
				String id = getWidgetTextValue(empStatusTable.getWidget(i,
						colId++));
				if (id != null && !id.isEmpty()) {
					status.setId(new EmploymentstatusId(i, person.getId()));
				} else {
					continue;
				}

				status.setEmpstatus(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setNeedWantMoreHours(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setTypeOfWork(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setHoursOfWork(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setJobRole(getWidgetTextValue(empStatusTable.getWidget(
						i, colId++)));
				status.setNameOfEmployer(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setIndustry(getWidgetTextValue(empStatusTable.getWidget(
						i, colId++)));
				status.setSizeOfCompany(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setSuburb(getWidgetTextValue(empStatusTable.getWidget(i,
						colId++)));
				status.setState(getWidgetTextValue(empStatusTable.getWidget(i,
						colId++)));

				// get start date
				HorizontalPanel hp = (HorizontalPanel) empStatusTable
						.getWidget(i, colId++);
				ListBox day = (ListBox) hp.getWidget(0);
				ListBox month = (ListBox) hp.getWidget(1);
				ListBox year = (ListBox) hp.getWidget(2);
				if (Tools.isValidDate(day, month, year)) {
					status.setStartDate(Tools.parseDate(day, month, year));
				}

				// get finish date
				hp = (HorizontalPanel) empStatusTable.getWidget(i, colId++);
				day = (ListBox) hp.getWidget(0);
				month = (ListBox) hp.getWidget(1);
				year = (ListBox) hp.getWidget(2);
				if (Tools.isValidDate(day, month, year)) {
					status.setFinishDate(Tools.parseDate(day, month, year));
				}

				status.setWorkingConditions(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setUnionMember(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				status.setReasonforleaving(getWidgetTextValue(empStatusTable
						.getWidget(i, colId++)));
				// status
				// .setNoHoursEmployedWeekly(getWidgetTextValue(empStatusTable
				// .getWidget(i, colId++)));
				// status.setNeedWantMoreHours(getWidgetTextValue(empStatusTable
				// .getWidget(i, colId++)));
				status.setJobNo(getWidgetTextValue(empStatusTable.getWidget(i,
						colId++)));
				statusList.add(status);
			}
			personService.saveEmploymentStatus(statusList, true,
					new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							GWT.log("Error saving employment status", caught);

						}

						@Override
						public void onSuccess(Void result) {
							clear();
							initialise();
						}
					});
		}
		return (T) statusList;
	}

	private String getWidgetTextValue(Widget widget) {
		String text = null;
		try {
			if (widget instanceof TextBox) {
				TextBox tb = (TextBox) widget;
				text = tb.getValue();
			} else if (widget instanceof HTML) {
				HTML lb = (HTML) widget;
				text = lb.getText();
			} else if (widget instanceof ListBox) {
				ListBox lb = (ListBox) widget;
				text = lb.getValue(lb.getSelectedIndex());
			}
		} catch (Exception e) {
		}

		return text;
	}

	public void populateEmploymentStatus(
			final List<Employmentstatus> employmentStatus) {
		if (employmentStatus != null) {
			for (Employmentstatus status : employmentStatus) {
				addEmpStatus(status.getEmpstatus(), status
						.getNeedWantMoreHours(), status.getJobNo(), status
						.getJobRole(), status.getNameOfEmployer(), status
						.getSuburb(), status.getState(), status
						.getSizeOfCompany(), status.getIndustry(), status
						.getStartDate(), status.getFinishDate(), status
						.getTypeOfWork(), status.getHoursOfWork(), status
						.getNoHoursEmployedWeekly(), status
						.getNeedWantMoreHours(), status.getWorkingConditions(),
						status.getUnionMember(), status.getReasonforleaving());
			}
		}
	}

	public PersonServiceAsync getPersonService() {
		return personService;
	}

	@Override
	public void createNewRecord() {
		// TODO Auto-generated method stub

	}

}
